package com.lee.main;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author
 * @create 2018-05-14 16:59
 **/
public class TestOkHttpPost {



  private static final byte[] LOCKER = new byte[0];
  private static TestOkHttpPost mInstance;
  private OkHttpClient mOkHttpClient;

  private TestOkHttpPost() {
    okhttp3.OkHttpClient.Builder ClientBuilder = new okhttp3.OkHttpClient.Builder();
    ClientBuilder.readTimeout(30, TimeUnit.SECONDS);//读取超时
    ClientBuilder.connectTimeout(10, TimeUnit.SECONDS);//连接超时
    ClientBuilder.writeTimeout(60, TimeUnit.SECONDS);//写入超时
    mOkHttpClient = ClientBuilder.build();
  }

  public static TestOkHttpPost getInstance() {
    if (mInstance == null) {
      synchronized (LOCKER) {
        if (mInstance == null) {
          mInstance = new TestOkHttpPost();
        }
      }
    }
    return mInstance;
  }



  public String httpPost(String __url,String content) throws IOException {
    Request.Builder builder =  new Request.Builder();
    RequestBody requestBody  = RequestBody.create(MediaType.parse("application/json"),content);

    builder.url(__url);
    builder.post(requestBody);


    Call call = this.mOkHttpClient.newCall(builder.build());
    Response response = call.execute();
    String ss = "";
    if(response.code() == 200)
      ss = response.body().string();
    else
      throw new IOException(__url + "Get Error" + Optional.ofNullable(response.body().string()).orElse(""));

    return ss;

  }



  public InputStream httpGet(String __url,Map<String,String> header) throws IOException {
    Request.Builder builder =  new Request.Builder();
//    RequestBody requestBody  = RequestBody.create(MediaType.parse("application/json"),content);

    Iterator it = header.keySet().iterator();
    while(it.hasNext())
    {
      String key = (String) it.next();
      builder.addHeader(key,header.get(key));
    }



    builder.url(__url);
    builder.get();


    Call call = this.mOkHttpClient.newCall(builder.build());
    Response response = call.execute();
    String ss = "";
    System.out.println(response.code());
    if(response.code() == 200 || response.code() == 304 ) {
//      ss = response.body().string();
      return response.body().byteStream();

    }
    else
      throw new IOException(__url + " Get Error " + Optional.ofNullable(response.body().string()).orElse(""));

//    return null;

  }




}
